package net.uman.framework.modules.security.springsecurity;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.uman.framework.modules.utils.DESCoder;
import net.uman.framework.modules.utils.EncodeUtils;


public class CaptchaFilter implements Filter {
	/**
	 * 判断用户输入的验证码是否正确
	 */
	private static final long serialVersionUID = -5838154525730151323L;

	public void init(FilterConfig config) throws ServletException {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String username = request.getParameter("j_username");
		String userpassword = request.getParameter("j_password");
		try {
			request.getSession(true).setAttribute("username", EncodeUtils.hexEncode(DESCoder.encrypt(username).getBytes()));
			request.getSession(true).setAttribute("userpassword", EncodeUtils.hexEncode(DESCoder.encrypt(userpassword).getBytes()));
		} catch (Exception e) {
			e.printStackTrace();
		}		
		String code = request.getParameter("captcha");
		String captcha =  (String)request.getSession().getAttribute("CAPTCHA");
		request.getSession(true).removeAttribute("errorMessage");
//		if(!StringUtils.equals(captcha, code)){
//			request.getSession(true).setAttribute("errorMessage", "需要输入正确的验证码，请重试！");
//			response.sendRedirect("login.action?error=true");
//		} else {
			filterChain.doFilter(request, response);
//		}
	}
}